package com.circle.view;

import com.circle.contrller.ExportController;
import com.circle.contrller.InternalFileController;
import com.circle.model.entity.DccInternalFileEntity;
import com.circle.model.module.DbDao;
import com.circle.model.module.log.LoggerABC;
import com.circle.model.module.log.LoggerBuilder;
import com.circle.model.util.DbDaoFactory;
import com.circle.model.util.DataConverter;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DocTable {
    private Component component;
    private DefaultTableModel tableModel;
    private JLabel totalLabel;
    private static final String[] COLUMN_NAMES = {
        "spec_no", "title", "rev", "owner_name", "dept_name", "deptid","doc_type"
    };
    private InternalFileController internalFileController;
    private ExportController exportController;
    //private List<Map<String, Object>> results;
    private String[] ids;

    public DocTable() {
    }

    public void setTableModel(DefaultTableModel tableModel) {
        this.tableModel = tableModel;
    }

    public void setTotalLabel(JLabel totalLabel) {
        this.totalLabel = totalLabel;
    }
    public void setComponent(Component component) {
        this.component = component;
    }

    public void search(){
        search("","","","");
    }
    public void search(String deptid, String deptName,String docType,String specNo) {
        LoggerABC loggerABC = LoggerBuilder.build();
        internalFileController = new InternalFileController();
        try {
            // 执行查询
            List<Map<String, Object>>  results = internalFileController.search(deptid, deptName, docType, specNo);
            updateTotalCount(results.size());
            // 清空现有数据
            while (tableModel.getRowCount() > 0) {
                tableModel.removeRow(0);
            }
            
            // 转换数据并添加到表格模型
            Object[][] data = DataConverter.toArray(results, COLUMN_NAMES);
            for (int i=0;i<data.length;i++) {
                Object[] row = data[i];
                tableModel.addRow(row);
            }
        } catch (Exception e) {
            e.printStackTrace();
            loggerABC.setException(e);
            loggerABC.logMessage(LoggerABC.ERROR,"Error occurred during search: " + e.getMessage());
        }
    }

    /**
     * 添加单行数据
     */
    public void addRow(Map<String, Object> rowData) {
        Object[] row = DataConverter.toArray(rowData, COLUMN_NAMES);
        tableModel.addRow(row);
    }

    // 添加更新方法
    private void updateTotalCount(int count) {
        // 确保在 EDT 线程中更新 UI
        SwingUtilities.invokeLater(() -> {
            totalLabel.setText(String.format("共 %d 条记录", count));
        });
    }

    //====================================================================

    public void export(String deptid, String deptName,String docType,String specNo) {
        exportController = new ExportController();
        //String[] idArray = DataConverter.toArraySingleField(results,"id");

        List<Map<String, Object>>  results = internalFileController.search(deptid, deptName, docType, specNo);
        List<DccInternalFileEntity> list = DataConverter.convertToEntityList(results);

        // 创建无标题栏的进度对话框
        JDialog progressDialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(component));
        progressDialog.setUndecorated(true); // 去掉标题栏和边框
        progressDialog.setLayout(new BorderLayout());
        progressDialog.setSize(300, 40); // 减小高度
        progressDialog.setLocationRelativeTo(null);

        // 设置圆角边框
        progressDialog.getRootPane().setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200), 1));

        JProgressBar progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true);
        progressBar.setString("正在导出...");
        progressBar.setBackground(Color.WHITE);
        progressBar.setForeground(new Color(24, 116, 205));

        progressDialog.add(progressBar, BorderLayout.CENTER);
        // 在新线程中执行导出操作
        new Thread(() -> {
            try {
                SwingUtilities.invokeLater(() -> progressDialog.setVisible(true));

                // 修改进度计算逻辑
                for (int i = 0; i < list.size(); i++) {
                    // 计算百分比进度
                    final int progressPercentage = (int)((i + 1.0) / list.size() * 100);
                    SwingUtilities.invokeLater(() -> {
                        progressBar.setValue(progressPercentage);
                        progressBar.setString(String.format("正在导出... %d%%", progressPercentage));
                    });
                    
                    DccInternalFileEntity internalFile = list.get(i);
                    exportController.exportSingle(internalFile);
                }
                
                // 设置为100%完成
                SwingUtilities.invokeLater(() -> {
                    progressBar.setValue(100);
                    progressBar.setString("导出完成 100%");
                });

                // 关闭进度对话框
                SwingUtilities.invokeLater(() -> {
                    progressDialog.dispose();
                    JOptionPane.showMessageDialog(component,
                            "导出完成！",
                            "提示",
                            JOptionPane.INFORMATION_MESSAGE);
                });

            } catch (Exception ex) {
                SwingUtilities.invokeLater(() -> {
                    progressDialog.dispose();
                    JOptionPane.showMessageDialog(component,
                            "导出失败：" + ex.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }



}